package com.esender.userpoints.service.impl;

import com.esender.userpoints.mapper.UserPointMapper;
import com.esender.userpoints.service.UserPointsConsume;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class UserPointsConsumeImpl implements UserPointsConsume {
    @Resource
    private UserPointMapper userPointMapper;
    private static final String ID_NAME = "spring_returned_message_correlation";

    @Override
    public void consume(Message message) throws InterruptedException {
        // 第一步，先查询幂等表是否存在当前消费标识
        String msgId = message.getMessageProperties().getHeader(ID_NAME);
        int count = userPointMapper.findById(msgId);
        // 如果存在说明已经被消费直接return
        if (count == 1){
            log.info("幂等处理，消息已被消费，消息ID：{}",msgId);
            return;
        }
        // 如果不存在，记录到幂等表，然后执行消费逻辑
        // 因为主键有唯一约束，也可以避免多线程环境下的写入判断问题
        userPointMapper.save(msgId);
        Thread.sleep(400);
        System.out.println("扣除用户积分成功！！");
    }
}
